package org.beetl.sql.core.db;

import org.beetl.sql.core.range.RangeSql;

import java.util.Map;

/**
 * 使用Oralce 新的翻页方式
 * @author lijiazhi
 */
public class Oracle12Style extends OracleStyle {

	Oracle12OffsetRange offsetRange = null;
    public Oracle12Style() {
		offsetRange = new Oracle12OffsetRange(this);
    }

	@Override
	public RangeSql getRangeSql() {
		return offsetRange;
	}

	public static class Oracle12OffsetRange implements RangeSql {
		AbstractDBStyle dbStyle = null;
		public Oracle12OffsetRange(AbstractDBStyle dbStyle){
			this.dbStyle = dbStyle;
		}
		@Override
		public String toRange(String jdbcSql, Object objOffset, Long limit) {
			Long offset = ((Number)objOffset).longValue();
			offset = PageParamKit.oracleOffset12(dbStyle.offsetStartZero, offset);
			StringBuilder builder = new StringBuilder(jdbcSql);
			builder.append(" OFFSET ");
			builder.append(offset);
			builder.append(" ROWS");
			builder.append(" FETCH NEXT ");
			builder.append(limit);
			builder.append(" ROWS ONLY ");
			return builder.toString();
		}

		@Override
		public String toTemplateRange(Class mapping,String template) {

			String pageSql = template+" OFFSET "+dbStyle.appendExpress(DBAutoGeneratedSql.OFFSET )
				+ " ROWS "
				+ " FETCH NEXT "
				+ dbStyle.appendExpress(DBAutoGeneratedSql.PAGE_END )
				+ " ROWS ONLY ";

			return pageSql;

		}

		@Override
		public void addTemplateRangeParas(Map<String, Object> paras, Object objOffset, long size) {

			long s = PageParamKit.oracleOffset12(dbStyle.offsetStartZero, (Long)objOffset);
			paras.put(DBAutoGeneratedSql.OFFSET, s);
			paras.put(DBAutoGeneratedSql.PAGE_END, size);
		}
	}

}
